from flask import Blueprint, render_template, session, g, request, render_template_string, redirect
from sqlalchemy import func

from application import app, db
from common.libs.Helper import ops_render, iPagenation
from common.libs.UrlManager import UrlManager
from common.models.movie_cat import MovieCat

# from common.models.user import User

index_page = Blueprint("index_page", __name__)


@index_page.route('/')
def index():
    req = request.values
    order_by=str(req['order']) if 'order' in req and req['order'] else "latest"
    page = 1
    if 'p' in req and req['p']:
        # try:
        page = int(req['p'])
        # except:
        #     return redirect(UrlManager.buildUrl('/error/404'))

    query = MovieCat.query

    page_size = 30

    total_count = query.count()

    page_params = {
        'total_count': total_count,
        'page_size': page_size,
        'page': page,
        'url': "/?"
    }

    pages = iPagenation(page_params)

    """
    0-30,30-60,60-90
    """
    # page=pages['page']
    print(page)
    if page > pages['total_pages']:
        return redirect(UrlManager.buildUrl('/error/404'))

    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    if order_by =="hot":
        list_of_movie = query.order_by(MovieCat.view_counter.desc(),MovieCat.id.desc())[offset:limit]
    else:
        list_of_movie = query.order_by(MovieCat.pub_date.desc(),MovieCat.id.desc())[offset:limit]
    return ops_render("index.html", {"data": list_of_movie, 'pages': pages})
    """
    name = "lingqin"

    context = {"name": name}
    context['user'] = {'nickname': "CodeCat"}
    context['num_list'] = [1, 2, 3, 4, 5]
    # from sqlalchemy import text
    # from application import db
    # sql = text("select * from `user`")
    # result = db.engine.execute(sql)
    # result = User.query.all()
    # 减少拼接字符串引起的不安全行为,避免被sql注入脱库
    result = User.query.all()
    # print(result)
    context['result'] = result
    # app.logger.info(session['uid'])
    return ops_render('index.html', context)
    """


@index_page.route("/info")
def info():
    req = request.values
    id = int(req['id']) if 'id' in req else 0
    if id < 1:
        return redirect(UrlManager.urlBuilder('/'))
    info = MovieCat.query.filter_by(id=id).first()
    if not info :
        return redirect(UrlManager.urlBuilder('/'))

    """
    更新阅读数
    """
    info.view_counter += 1
    db.session.add(info)
    db.session.commit()

    """
    获取推荐
    """

    recommand_list = MovieCat.query.order_by(func.rand()).limit(4)

    return ops_render("info.html", {'info': info, 'recommand_list': recommand_list})
